﻿using Microsoft.AspNetCore.Mvc.ModelBinding.Validation;

namespace net8.Validation
{
    public class ValidUrlAttribute : Attribute, IModelValidator
    {
        public string ErrorMessage { get; set; }

        public IEnumerable<ModelValidationResult> Validate(ModelValidationContext context)
        {
            ///应用在属性上
            string url = context.Model as string;
            if (url != null && Uri.IsWellFormedUriString(url, UriKind.Absolute))
            {
                return Enumerable.Empty<ModelValidationResult>();
            }

            return new List<ModelValidationResult> { new ModelValidationResult(string.Empty, ErrorMessage) };
        }
    }
}
